from PySide6.QtWidgets import QApplication, QMenu, QMainWindow, QWidget, QSystemTrayIcon
from PySide6.QtGui import QIcon
# from PySide6 import QtCore
# from PySide6 import QtWidgets
from PySide6 import QtCore, QtWidgets, QtGui
import os
import sched
import time
import _thread as thread
import threading
import myUtils
import configWin
import json


class BallWindow(QMainWindow):
    def __init__(self, main):
        super().__init__()
        self.main = main

        self.setWindowTitle('Ball Window')
        # 置顶加无边框
        self.setWindowFlags(QtCore.Qt.WindowType.FramelessWindowHint | QtCore.Qt.WindowType.WindowStaysOnTopHint | QtCore.Qt.WindowType.Tool)
        self.setWindowFlag(QtCore.Qt.WindowType.X11BypassWindowManagerHint)
        self.setAttribute(QtCore.Qt.WidgetAttribute.WA_TranslucentBackground)
        self.setFixedSize(100, 100)

        self.label_2 = QtWidgets.QLabel(self)
        self.label_2.setGeometry(QtCore.QRect(0, 0, 79, 24))
        self.label_2.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.label_2.setText("哈哈")
        self.label_2.setStyleSheet(
            "QLabel{background-color:rgba(166, 166, 166, 66);color:#000;border: 0px solid gray;}")
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor(255, 0, 0, 128))
        self.label_2.setPalette(palette)

        self.label_3 = QtWidgets.QLabel(self)
        self.label_3.setGeometry(QtCore.QRect(0, 24, 79, 24))
        self.label_3.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.label_3.setText("余：01:57")
        self.label_3.setStyleSheet(
            "QLabel{background-color:rgba(166, 166, 166, 66);color:#000;border: 0px solid gray;}")
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.ColorRole.Window, QtGui.QColor(255, 0, 0, 128))
        self.label_3.setPalette(palette)

        self.loadConfig(False)

        if self.param_dict['is_show_remaining_time'] != '1':
            self.label_3.hide()

        # 创建子线程
        t = threading.Thread(target=self.runPrice)
        # 设置为守护线程
        t.daemon = True
        # 启动子线程
        t.start()
        self.t = t

        t2 = threading.Thread(target=self.runTime)
        t2.daemon = True
        t2.start()
        self.t2 = t2

    def mouseDoubleClickEvent(self, event):
        if event.button() == QtCore.Qt.MouseButton.LeftButton:
            print("左键双击")
            self.main.open_config_window()

    def mousePressEvent(self, event):
        self.Point = QtGui.QCursor.pos()
        self.poor = 0
        if event.button() == QtCore.Qt.MouseButton.LeftButton:
            self.poor = self.Point - self.pos()
        else:
            if self.label_3.isVisible():
                self.label_3.hide()
            else:
                self.label_3.show()

    def mouseMoveEvent(self, event):
        if self.poor:
            self.startPoint = QtGui.QCursor.pos()
            self.move(self.startPoint - self.poor)

    def closeEvent(self, event):
        print("close ball")
        pass

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
        painter.setBrush(QtGui.QColor(255, 255, 255, 0))
        painter.setPen(QtCore.Qt.PenStyle.NoPen)
        painter.drawRoundedRect(self.rect(), 10, 10)

    def loadConfig(self, isInit):
        home_dir = os.path.expanduser("~")
        config_dir = home_dir + "\\AppData\\Local\\Moyu"
        config_path = config_dir + "\\config.json"

        if os.path.exists(config_path) and not isInit:
            print('文件存在')
            f = open(config_path, 'r')
            param_dict = json.loads(f.read())
            f.close()
        else:
            if not os.path.exists(config_dir):
                os.makedirs(config_dir)
            # 默认设置
            param_dict = {"working_days": "21.75", "working_hours": "09:00-17:00", "monthly_pay": "5000",
                          "refresh_interval_seconds": "0.2", "is_show_remaining_time": "0"}
            param_json = json.dumps(param_dict, sort_keys=False, indent=4, separators=(",", ": "))
            f = open(config_path, "w")
            f.write(param_json)
            f.close()

            print('文件不存在')
        self.param_dict = param_dict
        self.initSecondsUnitPrice()
        if self.param_dict['is_show_remaining_time'] != '1':
            self.label_3.hide()
        else:
            self.label_3.show()
    def initSecondsUnitPrice(self):
        s1 = float(self.param_dict['monthly_pay'])  # 月薪
        s2 = float(self.param_dict['working_days'])  # 计薪天数
        self.secondsUnitPrice = s1 / s2 / myUtils.getWorkingHours(self.param_dict['working_hours']) / 60 / 60

    def runPrice(self):
        # 暂停一会儿，以免还没有show()就进入self.isHidden()
        self.label_2.setText(".")
        time.sleep(0.2)
        self.label_2.setText("..")
        time.sleep(0.2)
        self.label_2.setText("...")
        time.sleep(0.2)
        self.label_2.setText("....")
        time.sleep(0.2)
        self.label_2.setText(".....")
        time.sleep(0.2)
        self.label_2.setText("......")
        while True:
            if self.isHidden():
                break
            time.sleep(float(self.param_dict['refresh_interval_seconds']))
            s = myUtils.getPastSeconds(self.param_dict['working_hours']) * self.secondsUnitPrice
            self.label_2.setText("%.4f" % s)
        print("子线程执行完毕...")

    def runTime(self):
        # 余：01:57
        # 暂停一会儿，以免还没有show()就进入self.isHidden()
        self.label_3.setText("xxx")
        time.sleep(1)
        while True:
            if self.isHidden():
                break
            time.sleep(1)
            text = myUtils.getRunTimeText(self.param_dict['working_hours'])
            self.label_3.setText(text)
        print("子线程执行完毕...")
